package com.uinnova.product.eam.workable.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 将主流程分配的变量解析到流程中,例如：流程中视图类型不同网关执行的路径也不同
 *
 * @author lichong
 * @since 2023/6/15 17:09
 */
@Slf4j
@Service("parseTaskVariableListener")
public class ParseTaskVariableListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) {
        Object childVariable = execution.getVariable("childVariable");
        Map<String, Object> variables = execution.getVariables();
        if (childVariable != null) {
            log.info("子流程变量：{}", childVariable);
            if (childVariable instanceof String) {
                String jsonString = (String) childVariable;
                try {
                    JSONObject jsonObject = JSON.parseObject(jsonString);
                    variables.putAll(jsonObject);
                    execution.setVariables(variables);
                } catch (Exception e) {
                    log.error("解析子流程变量异常", e);
                }
            }
        }
    }
}
